package com.totobox.apps.activity;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.totobox.apps.Const;
import com.totobox.apps.R;
import com.totobox.apps.common.FileUtils;

public class FileDownExceuteActivity3 extends BasicActivity {

	private Button btn_wait;
	private Button btn_cancel;
	
	private List<String> downList;
	public LinearLayout down_list;
	
	private ProgressDialog progressDialog;
	final private int PROGRESS_DIALOG = 0;
	final private int ALERT_DIALOG= 1;
	
	public Thread dataThread = null;
	public Handler handler = new Handler();
	
	public List<ProgressBar> pbList = new ArrayList<ProgressBar>();
	public List<TextView> txtList = new ArrayList<TextView>();
	
	public int totalCnt = 0;
	private TextView progressTxt;
	public FileDownloadTask downTask;
	
	public int curPos = 0;
	public boolean isStop = false;
	//public boolean isContinue= false;
	public boolean isCanceled = false;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.multi_file_download);
		
		progressTxt = (TextView) findViewById(R.id.total_file);
		
		btn_wait = (Button) findViewById(R.id.btn_wait);
		btn_cancel = (Button) findViewById(R.id.btn_cancel);
		btn_wait.setOnClickListener(this);
		btn_cancel.setOnClickListener(this);
		
		down_list = (LinearLayout) findViewById(R.id.down_list);
		
		//상단 타이틀 초기화
        super.initTitle();

        //진행 프로세스
		showDialog(PROGRESS_DIALOG);
		
		dataThread = new Thread(null, downData);
    	dataThread.start();
    	
	}

	@Override
	public void onClick(View v) {
		
		if(v == btn_wait){
			if(!isStop){
				isStop = true;
				btn_wait.setText("이어받기");
				try{ downTask.onCancelled(); }catch(Exception e){}
			}
			else{
				isStop = false;
				btn_wait.setText("다운중지");
				try{
					downTask = new FileDownloadTask();
					downTask.execute();
				}catch(Exception e){}
			}
		}
		
		if(v == btn_cancel){
			isStop = true;
			try{ downTask.onCancelled(); }catch(Exception e){}
			finish();
		}
		//이전 액티비티 이동
		if(v == btn_title_left){
			finish();
		}
			
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		return false;
	}

	/**
	 * 다운로드 파일 리스트
	 */
	private Runnable downData = new Runnable() {
    	public void run() {
    		try {
    			
    			downList = new ArrayList<String>();
    			downList.add("http://gundals.cafe24.com/Heaven.mp3");
    			downList.add("http://gundals.cafe24.com/Electric_Shock.mp3");
    			downList.add("http://gundals.cafe24.com/2HOT.mp3");
    			downList.add("http://gundals.cafe24.com/2HOT.mp3");
    			downList.add("http://gundals.cafe24.com/2HOT.mp3");
    			downList.add("http://gundals.cafe24.com/2HOT.mp3");
		    	handler.post(dataResults);
		    	
    		} catch (Exception e) {
    			Log.d("partData : ", e.toString());
    		}
    	}
    };
    
    /**
     * 
     */
	private Runnable dataResults = new Runnable() {
    	public void run() {
    		try {
    			if (downList != null) {
    				totalCnt = downList.size();
    				//checkFinishDown(0);
    				
    				for(int i = 0 ; i < totalCnt ; i++){
    					down_list.addView(addDownList(i));
    				}
    			}
    			else{
    				showNotFoundData();
    			}
    			
    	    	progressDialog.dismiss();
    	    	FileDownExceuteActivity3.this.removeDialog(PROGRESS_DIALOG);
    	    	
    	    	downTask = new FileDownloadTask();
				downTask.execute();
				
    		} catch (Exception e) {
    			Log.e("xml-data", e.toString());
    		}

    	}
    };
    
    private void showNotFoundData() {
    	Toast toast = Toast.makeText(this, "다운로드 파일이 없습니다.", Toast.LENGTH_SHORT);
    	toast.show();
    }
    
	@Override
	protected Dialog onCreateDialog (int id) {
		switch (id) {
		case PROGRESS_DIALOG:
			
			progressDialog = new ProgressDialog(this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("다운 목록 로딩중 입니다.");
			return progressDialog;
		case ALERT_DIALOG:
			return null;
		default:
			
			return null;
		}
	}
	
	
	public View addDownList(int position){
		
		LayoutInflater inflater = this.getLayoutInflater();
		View vw = inflater.inflate(R.layout.down_progress, null);
		
		ProgressBar progressBar = (ProgressBar)vw.findViewById(R.id.dn_progress_bar);
		progressBar.setId(position);
		
		TextView txtView = (TextView)vw.findViewById(R.id.down_per);
		txtView.setText("0 %");
		
		pbList.add(progressBar);
		txtList.add(txtView);
		
		return  vw;
	}
	
	/**
     * 
     * @param i
     */
	public void checkFinishDown(int pos) {
		//현재 포지션
		curPos = pos;
		progressTxt.setText("다운로드 진행률 "+(pos+1)+" / " +totalCnt);
	}
	
	
	/**
	 * 파일 다운로드
	 * @author taesu.yoo
	 *
	 */
	class FileDownloadTask extends AsyncTask<String, Integer, String> {

		String filename = "";
		String downDir = Const.homeDir + Const.movieDir;
		
		static final int DOWNLOAD_DONE = 0;
	    static final int DEFAULT_TIMEOUT = 30000;
	    
		boolean isCanceled = false;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			FileUtils.setMakeDir(downDir);
			//showDialog(DIALOG_DOWNLOAD_PROGRESS);
		}

		
		@Override
		protected String doInBackground(String... strData) {
			
			BufferedInputStream bis = null;
			long remains = 0, lenghtOfFile = 0;
			DefaultHttpClient client = null;
			
			byte buffer[] = new byte[1024];
			
			InputStream is = null;  
             
			for(int i = curPos  ; i < totalCnt ; i++){
				
				Log.e("curPos ",">>>>>>>>>> "+curPos);
				
				try{
		        	
					String http_url = downList.get(i);
					filename = downDir + getFileName(http_url);
					
					publishProgress(i , 0);
					
					File file = new File(filename);
					HttpGet request = new HttpGet(http_url);
					RandomAccessFile raf = null;
					long totalSize = 0;
					
					if(file.exists() == true){
						
                        //set range header & download only part of remaining contents.
						long len = file.length();
						
						raf = new RandomAccessFile(file , "rw");
						
				        totalSize = raf.length();
				        
						if(len > totalSize)         //if resource size is too big, remove it.
							file.createNewFile();   
						else
							request.addHeader("Range", "bytes=" + String.valueOf(totalSize) + "-");
						
	                }else{
	                        file.createNewFile();   
	                }
					
					client = new DefaultHttpClient();
                    HttpResponse resp =  client.execute(request);
                    HttpEntity content =  resp.getEntity();
                    
                    bis = new BufferedInputStream(content.getContent());
                    
                    long contentLen = content.getContentLength();
                    int count = 0;
                    long total = totalSize;
                    
                    while ((count = bis.read(buffer)) != -1 && !isStop) {
                    	
                    		total += count;
                    		
                    		publishProgress(i , (int) (total * 100 / contentLen));
                    		
                            raf.write(buffer, 0, count);
                    }
			        
                    if(isStop) break;
                    
		        } catch (Exception e) {
		        	//Log.e("down - ing ",e.getMessage());
	            } finally {
	                try{ if( bis != null ) bis.close(); }catch(Exception ex){}
	            }
			}
			
			return null;
		}
		
		@Override
		protected void onCancelled() {
			
			isCanceled = true;
			new File(downDir + filename).delete();
			//finish();
			super.onCancelled();
		}

		// publishProgress(…) 메소드 호출의 callback
		@Override
		protected void onProgressUpdate(Integer... args) {
			 
			Log.e("args[0] :  ",">>>>>> "+args[1]+" <<<<<");
			
			pbList.get(args[0]).setProgress(args[1]);
			txtList.get(args[0]).setText(args[1] + "%");
			
			//진행율 업데이트
			if(curPos < (args[0]+1)){
				//curPos = args[0]+1;
				checkFinishDown(curPos);
			}
		}

		@Override
		protected void onPostExecute(String unused) {
			if(isCanceled)
				new File(downDir + filename).delete();
		}
	}
	
	/**
	 * 파일명 생성
	 * @param wholePath
	 * @return
	 */
	public String getFileName(String wholePath)
    {
        String name=null;
        int start,end;
        start=wholePath.lastIndexOf('/');
        end=wholePath.length();
        name=wholePath.substring((start+1),end);
        return name;
    }

}